using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using EntLibEC.Cmn;
using EntLibEC.Biz.Report;
using EntLibEC.Biz;

namespace EntLibEC.View.Report
{
	/// <summary>
	/// Summary description for SaleReport.
	/// </summary>
	public partial class SaleReportByDate : PageBase
	{

		protected EntLibEC.View.Cmn.Stock ucStock;
		protected EntLibEC.View.Cmn.YNStatus ucIsWholeSale;

		private int orderNumberSum = 0;
		private int outNumberSum = 0;
		private decimal totalMoneySum = 0;
		private decimal shipSum = 0;
		private decimal premiumSum = 0;
		private decimal paySum = 0;
		private decimal miscSum = 0;
		private decimal saleSum = 0;
		private decimal costSum = 0;
		private decimal refundCashSum = 0;
		private decimal refundCostSum = 0;		
		                                                                                                                   
		private decimal profitSum = 0;

	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			base.CheckAccess((int)AppEnum.Privilege.SaleReportSearch,true ,null);
			if ( !Page.IsPostBack )
			{
				ucStock.BindStock(true);
				ucIsWholeSale.BindStatus(true);
				txtDateFrom.Text = DateTime.Now.ToString(AppConst.DateFormat).Substring(0,7) + "-01";
				txtDateTo.Text = DateTime.Now.ToString(AppConst.DateFormat);

				btnExport.Enabled = false;
			}
			txtDateFrom.Attributes["onclick"]= "javascript:calendar()";
			txtDateTo.Attributes["onclick"]= "javascript:calendar()";
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);

		}
		#endregion

		private bool checkForm()
		{
			if ( !checkDate(txtDateFrom, "Date From") || !checkDate(txtDateTo, "Date To"))
				return false;

			return true;

		}
		private bool checkDate(TextBox txt, string txtName)
		{
			if ( txt.Text.Trim() == "")
			{
				Assert(lblMessage, txtName + " can't be empty", -1);
				return false;
			}
			else
			{
				try
				{
					Convert.ToDateTime(txt.Text.Trim());
				}
				catch
				{
					Assert(lblMessage, txtName + " format error", -1);
					return false;
				}
			}
			return true;

		}
		protected void btnSearch_Click(object sender, System.EventArgs e)
		{
			if ( !checkForm())
				return;
			Hashtable ht = new Hashtable(10);
			ht.Add("DateFrom", txtDateFrom.Text.Trim());
			ht.Add("DateTo", txtDateTo.Text.Trim());
			ht.Add("GroupBy", ddlGroupBy.SelectedItem.Value.ToString());

			if ( ucIsWholeSale.YNSysNo != AppConst.IntNull )
				ht.Add("IsWholeSale", ucIsWholeSale.YNSysNo);
			if ( ucStock.StockSysNo != AppConst.IntNull )
				ht.Add("StockSysNo", ucStock.StockSysNo);

			DataSet ds = ReportManager.GetInstance().GetSaleReportDs(ht);

			DataGrid1.DataSource = ConvertDs(ds);
			DataGrid1.DataBind();

			int rows = 0;
			if ( Util.HasMoreRow(ds) )
			{
				rows = ds.Tables[0].Rows.Count;
				btnExport.Enabled = true;
			}
			Assert(lblMessage, rows.ToString() + " record(s)", 1);
		}

		private DataSet ConvertDs(DataSet ds)
		{
			if ( !Util.HasMoreRow(ds))
				return null;

			ds.Tables[0].Columns.Add("TotalAmt");
			ds.Tables[0].Columns.Add("Profit");
			ds.Tables[0].Columns.Add("ProfitRate");

			ds.Tables[0].Columns.Add("ShipPriceCvt");
			ds.Tables[0].Columns.Add("PremiumAmtCvt");
			ds.Tables[0].Columns.Add("PayPriceCvt");
			ds.Tables[0].Columns.Add("MiscAmtCvt");
			ds.Tables[0].Columns.Add("SaleAmtCvt");
			ds.Tables[0].Columns.Add("CostCvt");
			ds.Tables[0].Columns.Add("RefundCashAmtCvt");
			ds.Tables[0].Columns.Add("RefundCostCvt");			
			ds.Tables[0].Columns.Add("RefundProfitRate");
			ds.Tables[0].Columns.Add("NetSaleAmtCvt");
			ds.Tables[0].Columns.Add("ActualProfitRate");
			
			foreach( DataRow dr in ds.Tables[0].Rows )
			{
				
				int orderNumber = Util.TrimIntNull(dr["ordernumber"]);
				if ( orderNumber != AppConst.IntNull)
					orderNumberSum += orderNumber;
				
				int outNumber = Util.TrimIntNull(dr["outnumber"]);
				if ( outNumber != AppConst.IntNull )
				{
					outNumberSum += outNumber;
					decimal ship = Util.TrimDecimalNull(dr["ShipPrice"]);
					decimal pay = Util.TrimDecimalNull(dr["PayPrice"]);
					decimal premium = Util.TrimDecimalNull(dr["PremiumAmt"]);
					decimal miscAmt = Util.TrimDecimalNull(dr["MiscAmt"]);

					dr["ShipPriceCvt"] = ship.ToString(AppConst.DecimalFormatWithGroup);
					dr["PayPriceCvt"] = pay.ToString(AppConst.DecimalFormatWithGroup);
					dr["PremiumAmtCvt"] = premium.ToString(AppConst.DecimalFormatWithGroup);
					//dr["MiscAmtCvt"] = (miscAmt/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    dr["MiscAmtCvt"] = (miscAmt).ToString(AppConst.DecimalFormatWithGroup);

					decimal saleAmt = 0;
					if ( chkIsWithPoint.Checked )
						saleAmt = Util.TrimDecimalNull(dr["SaleAmt_P"]);
					else
						saleAmt = Util.TrimDecimalNull(dr["SaleAmt"]);

                    //dr["SaleAmtCvt"] = (saleAmt/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    //dr["totalamt"] = ((saleAmt+miscAmt)/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    dr["SaleAmtCvt"] = (saleAmt).ToString(AppConst.DecimalFormatWithGroup);
                    dr["totalamt"] = ((saleAmt + miscAmt)).ToString(AppConst.DecimalFormatWithGroup);

					decimal cost = 0;
					if ( chkIsWithPoint.Checked)
						cost = Util.TrimDecimalNull(dr["cost_p"]);
					else
						cost = Util.TrimDecimalNull(dr["cost"]);

                    //dr["CostCvt"] = (cost/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    dr["CostCvt"] = (cost).ToString(AppConst.DecimalFormatWithGroup);

                    decimal profit = saleAmt - cost;
					//dr["profit"] = (profit/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    dr["profit"] = (profit).ToString(AppConst.DecimalFormatWithGroup);

					if ( saleAmt != 0)
						dr["profitRate"] = ( (profit / saleAmt) * 100).ToString(AppConst.DecimalFormat) + "%";
					else
						dr["profitRate"] = "N/A";
						

					decimal refundCash = 0;
					decimal refundCost = 0;
					decimal refundProfit = 0;
					//decimal refundProfitRate = 0;
					//decimal ActualProfitRate = 	profitRate;

					if(Util.TrimDecimalNull(dr["RefundCashAmt"]) != AppConst.DecimalNull)
					{
						if( chkIsWithPoint.Checked)
						{
							refundCash = Util.TrimDecimalNull(dr["RefundCashAmt"]) + Util.TrimDecimalNull(dr["RefundPointAmt"])/10m;
							refundCost = Util.TrimDecimalNull(dr["RefundCostAmt"]) + Util.TrimDecimalNull(dr["RefundCostPointAmt"]);						
						}					
						else
						{
							refundCash = Util.TrimDecimalNull(dr["RefundCashAmt"]);
							refundCost = Util.TrimDecimalNull(dr["RefundCostAmt"]);
						}	
						refundProfit = refundCash - refundCost;
						if ( refundCash != 0)
							dr["RefundProfitRate"] = ( (refundProfit / refundCash) * 100).ToString(AppConst.DecimalFormat) + "%";
						else
							dr["RefundProfitRate"] = "N/A";

						if ( saleAmt - refundCash != 0)
							dr["ActualProfitRate"] = ((((saleAmt - refundCash) - (cost - refundCost))/(saleAmt - refundCash)) * 100).ToString(AppConst.DecimalFormat) + "%" ;
						else
							dr["ActualProfitRate"] = "N/A";
					}
                    //dr["RefundCashAmtCvt"] = (refundCash/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    //dr["RefundCostCvt"] = (refundCost/1.17m).ToString(AppConst.DecimalFormatWithGroup);					
                    //dr["NetSaleAmtCvt"] = ((saleAmt - refundCash)/1.17m).ToString(AppConst.DecimalFormatWithGroup);
                    dr["RefundCashAmtCvt"] = (refundCash).ToString(AppConst.DecimalFormatWithGroup);
                    dr["RefundCostCvt"] = (refundCost).ToString(AppConst.DecimalFormatWithGroup);
                    dr["NetSaleAmtCvt"] = ((saleAmt - refundCash)).ToString(AppConst.DecimalFormatWithGroup);
                    
                    shipSum += ship;
					paySum += pay;
					premiumSum += premium;
					miscSum += miscAmt; //div by 1.17
					saleSum += saleAmt; //div by 1.17
					totalMoneySum += saleAmt+miscAmt; //div by 1.17
					costSum += cost; // div by 1.17
					profitSum += profit; //div by 1.17		
					refundCashSum += refundCash ;
					refundCostSum += refundCost ;

				}
			}
			return ds;
		}

		private string ToFooterString(int x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.IntFormatWithGroup);
		}
		private string ToFooterString(decimal x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.DecimalFormatWithGroup);
		}

		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.Footer)
			{
				e.Item.Cells[1].Text = ToFooterString(orderNumberSum);
				e.Item.Cells[2].Text = ToFooterString(outNumberSum);
				//e.Item.Cells[3].Text = ToFooterString(totalMoneySum/1.17m);
                e.Item.Cells[3].Text = ToFooterString(totalMoneySum);
				e.Item.Cells[4].Text = ToFooterString(shipSum);
				e.Item.Cells[5].Text = ToFooterString(premiumSum);
				e.Item.Cells[6].Text = ToFooterString(paySum);
                //e.Item.Cells[7].Text = ToFooterString(miscSum/1.17m);
                //e.Item.Cells[8].Text = ToFooterString(saleSum/1.17m);
                //e.Item.Cells[9].Text = ToFooterString(costSum/1.17m);
                //e.Item.Cells[10].Text = ToFooterString(profitSum/1.17m);
                e.Item.Cells[7].Text = ToFooterString(miscSum);
                e.Item.Cells[8].Text = ToFooterString(saleSum);
                e.Item.Cells[9].Text = ToFooterString(costSum);
                e.Item.Cells[10].Text = ToFooterString(profitSum);

				if ( saleSum != 0)
					e.Item.Cells[11].Text = ( (profitSum / saleSum) * 100).ToString(AppConst.DecimalFormat) + "%";
				else
					e.Item.Cells[11].Text = "N/A";

                //e.Item.Cells[12].Text = ToFooterString(refundCashSum/1.17m);
                //e.Item.Cells[13].Text = ToFooterString(refundCostSum/1.17m);

                e.Item.Cells[12].Text = ToFooterString(refundCashSum);
                e.Item.Cells[13].Text = ToFooterString(refundCostSum);

				if(refundCashSum != 0)
					e.Item.Cells[14].Text = ( ((refundCashSum - refundCostSum)/refundCashSum) * 100).ToString(AppConst.DecimalFormat) + "%";
				else
					e.Item.Cells[14].Text = "N/A";

				//e.Item.Cells[15].Text = ToFooterString((saleSum - refundCashSum)/1.17m);
                e.Item.Cells[15].Text = ToFooterString((saleSum - refundCashSum));
				
				if((saleSum - refundCashSum) != 0)
					e.Item.Cells[16].Text = ( (((saleSum - refundCashSum) - (costSum - refundCostSum))/(saleSum - refundCashSum)) * 100).ToString(AppConst.DecimalFormat) + "%";
				else
					e.Item.Cells[16].Text = "N/A";

			}

			if(chkIsWithRefund.Checked)
			{
				e.Item.Cells[4].Visible = false; //shipSum
				e.Item.Cells[5].Visible = false; //premiunSum
				e.Item.Cells[6].Visible = false ; //paySum   
			}
			else
			{
				e.Item.Cells[12].Visible = false; // refundCashSum
				e.Item.Cells[13].Visible = false; // refundCostSum
				e.Item.Cells[14].Visible = false; // refundProfitRate
				e.Item.Cells[15].Visible = false; // NetSaleAmt
				e.Item.Cells[16].Visible = false; // NetProfitRate
			}
		
		}

		protected void btnExport_Click(object sender, System.EventArgs e)
		{
			Util.ToExcel(DataGrid1, "Sale Report By Date", "");
		}
	}
}
